package com.sls.api.util;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;

import com.google.gson.Gson;
import com.sls.api.game.constant.Constant;
import com.sls.api.game.pojo.UserInfo;
import com.sls.api.game.servlet.SuperServlet;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.SocketDTO;

/**
 * 获取密钥
 * 
 * @author cx
 * 
 */
public class SecretKeyUtil extends SuperServlet {

	private static final long serialVersionUID = 1L;
	// private static Logger log = Logger.getLogger(SecretKeyUtil.class);
	private Gson gson = CommonUtil.gson();
	private static SecretKeyUtil instance = new SecretKeyUtil();

	private SecretKeyUtil() {
	}

	public static SecretKeyUtil getInstance() {
		return instance;
	}

	/**
	 * 获取密钥
	 * 
	 * @param userNo
	 * @return
	 * @throws DocumentException
	 */
	public String getKey(String userNo, HttpServletRequest req) {
		String key = "";
		UserInfo user = new UserInfo();
		user.setUserNo(userNo);
		Head head = new Head();
		head.setRequestId(UUID.randomUUID().toString());
		head.setServiceCode(Constant.GET_SECRET_KEY);
		head.setIp(IpUtil.getIpAddr(req));
		head.setUserId(userNo);
		SocketDTO dto = super.send(head, user);
		if (dto != null && dto.getHead() != null
				&& Constant.SUCCESS.equals(dto.getHead().getResponseCode())) {
			String body = dto.getBody();
			if (StringUtils.isNotEmpty(body)) {
				key = gson.fromJson(body, String.class);
				return key;
			}
		}
		return null;
	}
}
